/*
 * @lc app=leetcode.cn id=2 lang=java
 *
 * [2] 两数相加
 */

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

// @lc code=start
class Solution {
    /**
     * [1 ms, 100%], [41.5MB, 29.64%]
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode last = head;
        int carry = 0;
        while (l1 != null || l2 != null || carry == 1) {
            int value = carry;
            if (l1 != null) {
                value += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                value += l2.val;
                l2 = l2.next;
            }
            if (value > 9) {
                carry = 1;
                value -= 10;
            } else {
                carry = 0;
            }
            last.next = new ListNode(value);
            last = last.next;
        }
        return head.next;
    }
}
// @lc code=end

